package abaco.symbol;

import java.util.HashMap;

import abaco.Symbol;
import abaco.gui.Drawer;
import abaco.gui.Panel;

public abstract class Mathematical implements Symbol {
	protected Symbol parent = null;
	protected HashMap<String, Symbol> children = new HashMap<String, Symbol>();

	@Override
	public Symbol getSymbolParent() {
		return parent;
	}

	@Override
	public Mathematical setSymbolParent(Symbol parent) {
		this.parent = parent;
		return this;
	}

	@Override
	public Mathematical removeSymbolParent() {
		parent = null;
		return this;
	}

	@Override
	public Symbol getSymbolChild(String name) {
		return children.get(name);
	}

	@Override
	public HashMap<String, Symbol> getSymbolChildren() {
		return children;
	}

	@Override
	public Mathematical setSymbolChild(Symbol child, String name) {
		// remove child from original parent
		Symbol oldParent = child.getSymbolParent();
		if (null != oldParent) {
			String oldName = oldParent.getSymbolChildName(child);
			oldParent.removeSymbolChild(oldName);
		}
		// attach child for current instance
		child.setSymbolParent(this);
		children.put(name, child);
		return this;
	}

	@Override
	public String getSymbolChildName(Symbol child) {
		for (String name : children.keySet()) {
			if (children.get(name).equals(child)) {
				return name;
			}
		}
		return null;
	}

	@Override
	public Mathematical removeSymbolChild(String name) {
		// actually replace current for a text symbol
		setSymbolChild(new Text(), name);
		return this;
	}

	protected Panel getChildPanel(String name, Boolean makeFontSmaller) {
		Symbol child = getSymbolChild(name);
		Panel panel = (new Drawer(child)).getPanel();
		panel.setMakeFontSmaller(makeFontSmaller);
		return panel;
	}

	/**
	 * Get children LaTeX.
	 */
	protected String toLatex(String name) {
		if (!children.containsKey(name)) {
			return UNDEFINED_LATEX;
		}
		return children.get(name).toLatex();
	}
}
